<template>
 <el-card>
   <el-tabs v-model="editableTabsValue" type="border-card" tab-position="left"
            @tab-click="handleTabClick" >
     <el-tab-pane v-for="item in editableTabs" :label="item.title" :name="item.name">
       <div :id="`chat-container-${item.name}`" style="overflow-y: auto;height: 400px;width: 100%;border: #1989fa solid 5px;border-radius: 5px;">
         <ul :id="`chat-${item.name}`" style="list-style: none">
         </ul>
       </div>
       <el-input v-model="messages[item.name]" @keydown.enter.prevent="sendMessage(item.name)" type="text" style="width: 80%;"></el-input>
       <el-button @click="sendMessage(item.name)" type="primary" style="width:20%">发送</el-button>
     </el-tab-pane>
   </el-tabs>
 </el-card>

  <el-button @click="showHistory" type="danger">查询历史消息</el-button>

  <el-dialog title="历史消息" v-model="messageDialogVisible"
             :close-on-click-modal="false" style="width:70%;padding:40px;">
    <el-card>
      <el-form inline="inline">
        <el-form-item>
          <el-input v-model="searchMessage.message" @keydown.enter.prevent="loadMessage" placeholder="搜索聊天记录"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="custMessage" type="primary">显示客户信息</el-button>
          <el-button @click="csMessage" type="primary">显示客服信息</el-button>
          <el-button @click="resetMessage" type="primary">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card>
      <el-table :data="historyMessage" >
        <el-table-column type="index" label="编号" width="80" align="center"></el-table-column>
        <el-table-column prop="custName" v-if="colDisableCust" label="客户名" align="center">
          <template #default="scope" >
            <span v-if="scope.row.custName=='不存在'">{{scope.row.custName}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="csName" v-if="colDisableCs" label="客服名" align="center">
          <template #default="scope">
            <span v-if="scope.row.csName=='不存在'">{{scope.row.csName}}</span>
          </template>
        </el-table-column>
        <el-table-column  prop="message" label="消息" align="center"></el-table-column>
        <el-table-column  prop="createTime" label="发送时间" align="center"></el-table-column>
      </el-table>
    </el-card>
  </el-dialog>


</template>

<script setup>
import {nextTick, onMounted, ref, watch} from "vue";
import {ElMessage} from "element-plus";
import axios from "axios";
import router from "@/router";

const messages = ref({})
const messageArr = ref([])

const editableTabsValue=ref(1)
const editableTabs=ref([
  {title:'新会话',name:1},
])
const sockets=ref([])
let sessionArr=[]

const addTab = async () => {
  await axios.post(BASE_URL+'/v1/webSessionMessage/session/select',{custId:currentCust.value.id})
      .then((response)=>{
        if (response.data.code==2000){
          if (sessionArr.length===0){
            sessionArr=response.data.data
            if (sessionArr.length>0){
              editableTabs.value=[]
              let s=sessionArr[0]
              editableTabs.value.push({title: '客服'+s.csId+'号',name: 1,sessionId:s.id,times:0})
            }
          }

        }else {
          ElMessage.error(response.data.msg)
        }
      })
}


const handleTabClick = (item) => {
  if (!sockets.value[item.name]){
    initSocket(item)
  }
}
const initSocket = (tab) => {
  if (tab.name===undefined){
    return
  }

  const wsUrl = "ws://localhost:10900/chat";
  sockets.value[tab.name] = new WebSocket(wsUrl);

  sockets.value[tab.name].onmessage = function (event) {
    const data = JSON.parse(event.data);
    if (data.sessionId!=null){
      let boolean=true
      for (let e of editableTabs.value){
        if (e.sessionId===data.sessionId){
          boolean=false
          break
        }
      }
      if (boolean){
        addTab()

        //let name=editableTabs.value.length
        //editableTabsValue.value=name
        //messages.value[name]=data.message
        //sendMessage(name)
        return
      }
    }
    const chatElement = document.getElementById(`chat-${tab.name}`);
    if (chatElement) {
      if (data.csId == null) {
        chatElement.innerHTML += `<li style="text-align: right;margin-bottom: 10px;"><span style="border: black solid 1px;display: inline-block;margin-right: 10px;padding: 5px;word-break:break-word;text-align: left;">${data.message}</span><span>${data.custName}</span></li>`;
      } else {
        chatElement.innerHTML += `<li style="text-align: left;margin-bottom: 10px;"><span>${data.csName}</span><span style="border: black solid 1px;display: inline-block;margin-left: 10px;padding: 5px;word-break:break-word;text-align: left;">${data.message}</span></li>`;
        if (tab.name!==editableTabsValue.value){
          editableTabs.value[tab.name-1].time+=1
        }
      }
    }
  };

  sockets.value[tab.name].onopen = function (event) {
    if(currentCust.value.id==null){
      getCust()
    }
    if (!messageArr.value[tab.name]) {
      messageArr.value[tab.name] = {};
    }

    if (editableTabs.value[tab.name-1].sessionId!=null){
      messageArr.value[tab.name].sessionId=editableTabs.value[tab.name-1].sessionId
    }
    messageArr.value[tab.name].custId=currentCust.value.id
    messageArr.value[tab.name].custName=currentCust.value.username
    messageArr.value[tab.name].message="连接成功"

    sendMessage(tab.name)
    console.log("连接成功");
  };

  sockets.value[tab.name].onclose = function (event) {
    console.log("连接关闭", event.code, event.reason);
    reconnect=true
    if (event.code !== 1000) {
      console.log(`尝试重连...`);
      // 设置重连定时器
      reconnectTimeouts.value[tab.name] = setTimeout(() => {
        initSocket(tab); // 递归调用 initSocket 尝试重连
      }, 10000);
    }
  };

};
let reconnect=false
// 为每个 WebSocket 实例维护一个重连定时器
const reconnectTimeouts = ref({});


const sendMessage = (tabName) => {
  if (!messages.value[tabName]) {
    messages.value[tabName] = "";
  }
  if (messages.value[tabName] !== '' && messages.value[tabName].trim()) {
    messageArr.value[tabName].message = messages.value[tabName];
  }
  if (messageArr.value[tabName].message === "" || !messageArr.value[tabName].message.trim()) {
    ElMessage.error("请输入内容");
    messages.value[tabName] = "";
    return;
  }
  if (sockets.value[tabName]) {
    sockets.value[tabName].send(JSON.stringify(messageArr.value[tabName]));
  }
  messageArr.value[tabName].message = ""
  messages.value[tabName] = ""
  scrollToBottom(tabName)
}

const currentCust=ref({})
const scrollToBottom = (tabName) => {
  nextTick(() => {
    setTimeout(() => {
      const chatContainer = document.getElementById(`chat-container-${tabName}`);
      if (chatContainer) {
        chatContainer.scrollTop = chatContainer.scrollHeight;
      }
    }, 1);
  });
}

const historyMessage=ref([])
const searchMessage=ref({})
const messageDialogVisible=ref(false)

let sessionId
const showHistory = () => {
  messageDialogVisible.value=true
  sessionId=editableTabs.value[editableTabsValue.value-1].sessionId
  searchMessage.value={sessionId:sessionId}
  loadMessage()
}
const loadMessage = async () => {
  await axios.post(BASE_URL+'/v1/webSessionMessage/message/select',searchMessage.value)
      .then((response)=>{
        if (response.data.code==2000){
          historyMessage.value=response.data.data
          searchMessage.value={sessionId:sessionId}
        }else {
          ElMessage.error(response.data.msg)
        }
      })
}
const colDisableCs=ref(true)
const colDisableCust=ref(true)

const csMessage = () => {
  searchMessage.value={sessionId:sessionId}
  loadMessage().then(()=>{
    historyMessage.value=historyMessage.value.filter(item=>item.csId!=null)
  })
  colDisableCs.value=true
  colDisableCust.value=false
}
const custMessage = () => {
  searchMessage.value={sessionId:sessionId}
  loadMessage().then(()=>{
    historyMessage.value=historyMessage.value.filter(item=>item.custId!=null)
  })
  colDisableCs.value=false
  colDisableCust.value=true
}
const resetMessage = () => {
  searchMessage.value={sessionId:sessionId}
  loadMessage()
  colDisableCs.value=true
  colDisableCust.value=true
}




onMounted(async () => {
  await getCust(currentCust);
  initSocket(editableTabs.value[0]);
});
watch(editableTabsValue,(newVal)=>{
  handleTabClick({name:newVal})
})
</script>

<style scoped>

</style>